﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace KBEngine.Setting
{
    [Serializable]
    [XmlRoot("root")]
    public class ServerErrorsDefaults : IXmlSerializable
    {
        public List<Info> errorInfos = new List<Info>();

        public class Info
        {
            /// <summary>
            /// 错误Id
            /// </summary>
            public ushort id = 0;

            /// <summary>
            /// 错误名称
            /// </summary>
            public string name = string.Empty;

            /// <summary>
            /// 错误描述
            /// </summary>
            public string desc = string.Empty;
        }

        #region XmlSerializable
        public XmlSchema GetSchema() => null;
        public void ReadXml(XmlReader reader)
        {
            errorInfos.Clear();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            var root = xmlDoc.SelectSingleNode("root");
            foreach (XmlNode xmlNode in root.ChildNodes)
            {
                Info info = new Info();
                info.name = xmlNode.Name;
                if (xmlNode.SelectSingleNode("id").TryGetValue(out var txt))
                    info.id = ushort.Parse(txt);

                if (xmlNode.SelectSingleNode("descr").TryGetValue(out txt))
                    info.desc = txt;

                errorInfos.Add(info);
            }
        }
        public void WriteXml(XmlWriter writer)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement root = xmlDoc.CreateElement("root");
            xmlDoc.AppendChild(root);
            foreach (var item in errorInfos)
            {
                var node = xmlDoc.CreateElement(item.name);
                var idNode = xmlDoc.CreateElement("id");
                var descrNode = xmlDoc.CreateElement("descr");
                idNode.InnerText = item.id.ToString();
                descrNode.InnerText = item.desc;

                node.AppendChild(idNode);
                node.AppendChild(descrNode);
                root.AppendChild(node);
            }
            foreach (XmlNode item in root)
            {
                item.WriteTo(writer);
            }
        }
        #endregion
    }
}
